<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="第二章：对象、消息、运行期(1)“对象”是基本构造单元，可以通过对象来存储数据和传递数据。对象之间传递数据并执行任务的过程就叫做“消息传递”。 第6条：理解 “属性” 这一概念“属性” 是 Objective-C 的一项特性，用来封装对象中的数据。属性最终是通过实例变量来实现的，属性只是提供了一种简洁的抽象机制。 对象布局对象布局在编译期就已经确定了，当代码需要访问实例变量的时候，编译器会把其替换">
<meta property="og:type" content="article">
<meta property="og:title" content="《Effective Objective-C 2.0》第二章阅读笔记(1)">
<meta property="og:url" content="https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="第二章：对象、消息、运行期(1)“对象”是基本构造单元，可以通过对象来存储数据和传递数据。对象之间传递数据并执行任务的过程就叫做“消息传递”。 第6条：理解 “属性” 这一概念“属性” 是 Objective-C 的一项特性，用来封装对象中的数据。属性最终是通过实例变量来实现的，属性只是提供了一种简洁的抽象机制。 对象布局对象布局在编译期就已经确定了，当代码需要访问实例变量的时候，编译器会把其替换">
<meta property="og:locale">
<meta property="article:published_time" content="2018-04-16T16:00:00.000Z">
<meta property="article:modified_time" content="2018-07-01T08:14:25.801Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="Effective Objective-C 2.0">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/","path":"2018/04/2018/04/《Effective Objective-C 2.0》第二章阅读笔记(1)/","title":"《Effective Objective-C 2.0》第二章阅读笔记(1)"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>《Effective Objective-C 2.0》第二章阅读笔记(1) | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC%E4%BA%8C%E7%AB%A0%EF%BC%9A%E5%AF%B9%E8%B1%A1%E3%80%81%E6%B6%88%E6%81%AF%E3%80%81%E8%BF%90%E8%A1%8C%E6%9C%9F-1"><span class="nav-number">1.</span> <span class="nav-text">第二章：对象、消息、运行期(1)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC6%E6%9D%A1%EF%BC%9A%E7%90%86%E8%A7%A3-%E2%80%9C%E5%B1%9E%E6%80%A7%E2%80%9D-%E8%BF%99%E4%B8%80%E6%A6%82%E5%BF%B5"><span class="nav-number">1.1.</span> <span class="nav-text">第6条：理解 “属性” 这一概念</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AF%B9%E8%B1%A1%E5%B8%83%E5%B1%80"><span class="nav-number">1.1.0.1.</span> <span class="nav-text">对象布局</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%BA%94%E7%94%A8%E7%A8%8B%E5%BA%8F%E4%BA%8C%E8%BF%9B%E5%88%B6%E6%8E%A5%E5%8F%A3%EF%BC%88Application-Binary-Interface%EF%BC%8CABI%EF%BC%89"><span class="nav-number">1.1.0.2.</span> <span class="nav-text">应用程序二进制接口（Application Binary Interface，ABI）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#synthesize-amp-dynamic"><span class="nav-number">1.1.0.3.</span> <span class="nav-text">@synthesize &amp; @dynamic</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%B1%9E%E6%80%A7%E7%89%B9%E8%B4%A8"><span class="nav-number">1.1.0.4.</span> <span class="nav-text">属性特质</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%8E%9F%E5%AD%90%E6%80%A7"><span class="nav-number">1.1.0.4.1.</span> <span class="nav-text">原子性</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E8%AF%BB%E5%86%99%E6%9D%83%E9%99%90"><span class="nav-number">1.1.0.4.2.</span> <span class="nav-text">读写权限</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#copy"><span class="nav-number">1.1.0.4.3.</span> <span class="nav-text">copy</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC7%E6%9D%A1%EF%BC%9A%E5%9C%A8%E5%AF%B9%E8%B1%A1%E5%86%85%E9%83%A8%E5%B0%BD%E9%87%8F%E7%9B%B4%E6%8E%A5%E8%AE%BF%E9%97%AE%E5%AE%9E%E4%BE%8B%E5%8F%98%E9%87%8F%EF%BC%88%E6%84%9F%E8%A7%89%E6%9C%89%E6%AD%A7%E4%B9%89%EF%BC%89"><span class="nav-number">1.2.</span> <span class="nav-text">第7条：在对象内部尽量直接访问实例变量（感觉有歧义）</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AF%B9%E8%B1%A1%E5%86%85%E9%83%A8%E4%B8%8D%E8%A6%81%E7%9B%B4%E6%8E%A5%E8%AE%BE%E7%BD%AE%E5%AE%9E%E4%BE%8B%EF%BC%88%E6%9C%89%E6%AD%A7%E4%B9%89%EF%BC%89"><span class="nav-number">1.2.0.1.</span> <span class="nav-text">对象内部不要直接设置实例（有歧义）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96%E6%97%B6%E5%BA%94%E8%AF%A5%E7%9B%B4%E6%8E%A5%E8%AE%BF%E9%97%AE%E5%AE%9E%E4%BE%8B"><span class="nav-number">1.2.0.2.</span> <span class="nav-text">初始化时应该直接访问实例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%87%92%E5%8A%A0%E8%BD%BD"><span class="nav-number">1.2.0.3.</span> <span class="nav-text">懒加载</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC8%E6%9D%A1%EF%BC%9A%E7%90%86%E8%A7%A3-%E2%80%9C%E5%AF%B9%E8%B1%A1%E5%90%8C%E7%AD%89%E6%80%A7%E2%80%9D-%E8%BF%99%E4%B8%80%E6%A6%82%E5%BF%B5"><span class="nav-number">1.3.</span> <span class="nav-text">第8条：理解 “对象同等性” 这一概念</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AF%B9%E8%B1%A1%E5%AE%8C%E5%85%A8%E7%9B%B8%E7%AD%89"><span class="nav-number">1.3.0.1.</span> <span class="nav-text">对象完全相等</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89-%E2%80%9C%E7%9B%B8%E7%AD%89%E2%80%9D"><span class="nav-number">1.3.0.2.</span> <span class="nav-text">自定义 “相等”</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%85%B8%E5%9E%8B%E5%BA%94%E7%94%A8"><span class="nav-number">1.3.0.3.</span> <span class="nav-text">典型应用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%B3%A8%E6%84%8F"><span class="nav-number">1.3.0.4.</span> <span class="nav-text">注意</span></a></li></ol></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="《Effective Objective-C 2.0》第二章阅读笔记(1) | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《Effective Objective-C 2.0》第二章阅读笔记(1)
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-17 00:00:00" itemprop="dateCreated datePublished" datetime="2018-04-17T00:00:00+08:00">2018-04-17</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:14:25" itemprop="dateModified" datetime="2018-07-01T16:14:25+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第二章：对象、消息、运行期-1"><a href="#第二章：对象、消息、运行期-1" class="headerlink" title="第二章：对象、消息、运行期(1)"></a><center>第二章：对象、消息、运行期(1)</center></h1><p>“对象”是基本构造单元，可以通过对象来存储数据和传递数据。对象之间传递数据并执行任务的过程就叫做“消息传递”。</p>
<h2 id="第6条：理解-“属性”-这一概念"><a href="#第6条：理解-“属性”-这一概念" class="headerlink" title="第6条：理解 “属性” 这一概念"></a>第6条：理解 “属性” 这一概念</h2><p>“属性” 是 Objective-C 的一项特性，用来封装对象中的数据。属性最终是通过实例变量来实现的，属性只是提供了一种简洁的抽象机制。</p>
<h4 id="对象布局"><a href="#对象布局" class="headerlink" title="对象布局"></a>对象布局</h4><p>对象布局在编译期就已经确定了，当代码需要访问实例变量的时候，编译器会把其替换成偏移量，这个偏移量是“硬编码”，表示该变量距离对象内存起始地址有多远。<br>当类增加了实例变量时，原来的偏移量就已经不再适用，所以这时候需要重新编译。偏移量保存在类对象中，会在运行时查找。</p>
<h4 id="应用程序二进制接口（Application-Binary-Interface，ABI）"><a href="#应用程序二进制接口（Application-Binary-Interface，ABI）" class="headerlink" title="应用程序二进制接口（Application Binary Interface，ABI）"></a>应用程序二进制接口（Application Binary Interface，ABI）</h4><blockquote>
<p>应用程序二进制接口描述了应用程序和操作系统之间，一个应用和它的库之间，或者应用的组成部分之间的低层接口。ABI不同于应用程序接口（API），API定义了源代码和库之间的接口，因此同样的代码可以在支持这个API的任何系统中编译，然而ABI允许编译好的目标代码在使用兼容ABI的系统中无需改动就能运行。（百度百科）</p>
</blockquote>
<p>ABI定义了许多内容（标准），其中一项就是生成代码时所应遵循的规范，有了这种规范，我们就可以在分类和实现文件定义实例变量，可以将实例变量从接口文件中移开，以便保护和类实现相关的内部信息。</p>
<h4 id="synthesize-amp-dynamic"><a href="#synthesize-amp-dynamic" class="headerlink" title="@synthesize &amp; @dynamic"></a>@synthesize &amp; @dynamic</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">@implementation</span></span></span><br><span class="line"><span class="keyword">@synthesize</span> firstName = _myFirstName;</span><br><span class="line"><span class="keyword">@dynamic</span> firstName;</span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>
<p>@synthesize 用来指定实例变量的名称。<br>@dynamic 告诉编译器不要自动生成实例变量，也不要生成 setter 和 getter 方法。这时编译器不会报错，而是在运行时查找。</p>
<h4 id="属性特质"><a href="#属性特质" class="headerlink" title="属性特质"></a>属性特质</h4><p>原子性，读写权限，内存管理（assign、strong、weak、unsafe_unretained、copy），方法名</p>
<h5 id="原子性"><a href="#原子性" class="headerlink" title="原子性"></a>原子性</h5><p>iOS 开发的时候应该尽量使用 nonatomic，使用 atomic 会严重影响性能。</p>
<h5 id="读写权限"><a href="#读写权限" class="headerlink" title="读写权限"></a>读写权限</h5><p>readwrite 同时生成setter 和 getter 方法。<br>readonly 只生成 getter 方法。  </p>
<h5 id="copy"><a href="#copy" class="headerlink" title="copy"></a>copy</h5><p>当属性类型为 NSString 时，一定要用 copy 修饰，防止当传递过来的值是 NSMutableString 类型，从而可能会在不知情的情况下更改属性的值。</p>
<h2 id="第7条：在对象内部尽量直接访问实例变量（感觉有歧义）"><a href="#第7条：在对象内部尽量直接访问实例变量（感觉有歧义）" class="headerlink" title="第7条：在对象内部尽量直接访问实例变量（感觉有歧义）"></a>第7条：在对象内部尽量直接访问实例变量（感觉有歧义）</h2><p>在对象外面，应该通过属性访问实例变量。在对象内部，除了几种特殊的情况下，读取实例变量应该采用直接访问的形式，设置实例变量则采用属性来设置。</p>
<h4 id="对象内部不要直接设置实例（有歧义）"><a href="#对象内部不要直接设置实例（有歧义）" class="headerlink" title="对象内部不要直接设置实例（有歧义）"></a>对象内部不要直接设置实例（有歧义）</h4><p>这样做不会调用 setter 方法，也就绕过了相关属性定义的“内存管理语义”，比如使用了 copy 特质，直接访问不会拷贝该属性，只会保留新值并释放旧值。此外当设置了KVO时，直接设置实例也不会触发KVO。</p>
<h4 id="初始化时应该直接访问实例"><a href="#初始化时应该直接访问实例" class="headerlink" title="初始化时应该直接访问实例"></a>初始化时应该直接访问实例</h4><p>如果父类初始化使用 setter 方法设置属性，而子类又重写了这个 setter 方法，那么子类初始化时，父类也会初始化，这时父类将会调用子类的 setter 方法。<br>例外：如果待初始化的实例变量申明在父类中，而子类无法直接访问此实例变量，这时就需要调用 setter 方法了。</p>
<blockquote>
<p>dealloc 方法中也应该直接读写实例变量  </p>
</blockquote>
<h4 id="懒加载"><a href="#懒加载" class="headerlink" title="懒加载"></a>懒加载</h4><p>如果某个属性使用了懒加载，那就必须使用 getter 方法了。</p>
<h2 id="第8条：理解-“对象同等性”-这一概念"><a href="#第8条：理解-“对象同等性”-这一概念" class="headerlink" title="第8条：理解 “对象同等性” 这一概念"></a>第8条：理解 “对象同等性” 这一概念</h2><p>“对象同等性” 可以理解为某种意义上两个对象相等，这个“相等”是我们自定义的。官方给我们定义了一些判断两个对象是否“相等”的方法</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// NSString</span></span><br><span class="line">- (<span class="type">BOOL</span>)isEqualToString:(<span class="built_in">NSString</span> *)aString;</span><br><span class="line"></span><br><span class="line"><span class="comment">// NSData</span></span><br><span class="line">- (<span class="type">BOOL</span>)isEqualToData:(<span class="built_in">NSData</span> *)other;</span><br><span class="line"></span><br><span class="line"><span class="comment">// NSDictionary</span></span><br><span class="line">- (<span class="type">BOOL</span>)isEqualToDictionary:(<span class="built_in">NSDictionary</span>&lt;KeyType, ObjectType&gt; *)otherDictionary;</span><br></pre></td></tr></table></figure>

<h4 id="对象完全相等"><a href="#对象完全相等" class="headerlink" title="对象完全相等"></a>对象完全相等</h4><p>用 “&#x3D;&#x3D;” 判断两个对象是否是同一个对象，这里判断的是指针。</p>
<h4 id="自定义-“相等”"><a href="#自定义-“相等”" class="headerlink" title="自定义 “相等”"></a>自定义 “相等”</h4><p>通过 NSObject 协议中的两个方法自定义 “相等”。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">BOOL</span>)isEqual:(<span class="type">id</span>)object;  </span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">readonly</span>) <span class="built_in">NSUInteger</span> hash;</span><br></pre></td></tr></table></figure>
<p>自定义一个 Person 类，包含一个 email 属性。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">Person</span>()</span></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">copy</span>) <span class="built_in">NSString</span> *email;</span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>

<p>假定对象的 email 属性值相同，就认为这两个类“相同”，那么自定义方法如下：  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">BOOL</span>)isEqualToPerson:(Person *)otherPerson &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="literal">nil</span> == otherPerson) <span class="keyword">return</span> <span class="literal">NO</span>;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">self</span> == otherPerson) <span class="keyword">return</span> <span class="literal">YES</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> ([_email isEqualToString:otherPerson.email]) <span class="keyword">return</span> <span class="literal">YES</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">NO</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">BOOL</span>)isEqual:(<span class="type">id</span>)object &#123;</span><br><span class="line">    <span class="keyword">if</span> ([<span class="keyword">self</span> <span class="keyword">class</span>] != [object <span class="keyword">class</span>]) <span class="keyword">return</span> <span class="literal">NO</span>;</span><br><span class="line">    </span><br><span class="line">    [<span class="keyword">self</span> isEqualToPerson:object];</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">NO</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果两个对象相等，则其哈希码一定相同。反之，如果哈希码相同，这两个对象不一定相同。</span></span><br><span class="line"><span class="comment">// 考虑到性能问题，hash 方法要保证高效率</span></span><br><span class="line">- (<span class="built_in">NSUInteger</span>)hash &#123;</span><br><span class="line">	<span class="comment">// 此处逻辑可以自定义</span></span><br><span class="line">    <span class="keyword">return</span> [_email hash];</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="典型应用"><a href="#典型应用" class="headerlink" title="典型应用"></a>典型应用</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// NSArray</span></span><br><span class="line">- (<span class="type">BOOL</span>)containsObject:(ObjectType)anObject;</span><br><span class="line"><span class="comment">// NSSet</span></span><br><span class="line">- (<span class="type">BOOL</span>)containsObject:(ObjectType)anObject;</span><br></pre></td></tr></table></figure>

<p>使用 NSArray 调用 containsObject 这个方法，会直接调用 isEqual 方法判断两个对象是否相等。测试发现这里并没有调用 hash 方法，原因不明，例子如下：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSMutableArray</span> *array = [<span class="built_in">NSMutableArray</span> array];</span><br><span class="line">Person *aPerson = <span class="literal">nil</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">	Person *p = [[Person alloc] initWithEmail:[<span class="built_in">NSString</span> stringWithFormat:<span class="string">@&quot;%zd&quot;</span>,i]];</span><br><span class="line">	[array addObject:p];</span><br><span class="line">	aPerson = p;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> ([array containsObject:aPerson]) &#123;</span><br><span class="line">	<span class="built_in">NSLog</span>(<span class="string">@&quot;array has &#x27;aPerson&#x27;&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>再使用 NSSet 看看是怎么执行的。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSMutableSet</span> *sets = [<span class="built_in">NSMutableSet</span> set];</span><br><span class="line">Person *aPerson = <span class="literal">nil</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">	Person *p = [[Person alloc] initWithEmail:[<span class="built_in">NSString</span> stringWithFormat:<span class="string">@&quot;%zd&quot;</span>,i]];</span><br><span class="line">	[sets addObject:p];</span><br><span class="line">	aPerson = p;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> ([sets containsObject:aPerson]) &#123;</span><br><span class="line">	<span class="built_in">NSLog</span>(<span class="string">@&quot;array has &#x27;aPerson&#x27;&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>NSSet 在 addObject 和 containsObject 方法中都会调用 hash 方法。再 addObject 方法中会调用 isEqual 方法，而 containsObject 方法中则不再调用。NSArray 则是在 containsObject 方法中调用 isEqual 方法。</p>
<blockquote>
<p>不同的集合会使用不同的逻辑判断是否“相等”。</p>
</blockquote>
<h4 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h4><p>在 NSSet 中， hash 方法是判断的第一步，应该保证此方法的高效性，同时也要考虑 <strong>哈希碰撞</strong> 发生的概率。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Effective-Objective-C-2-0/" rel="tag"># Effective Objective-C 2.0</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%80%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/" rel="prev" title="《Effective Objective-C 2.0》第一章阅读笔记">
                  <i class="fa fa-chevron-left"></i> 《Effective Objective-C 2.0》第一章阅读笔记
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(2)/" rel="next" title="《Effective Objective-C 2.0》第二章阅读笔记(2)">
                  《Effective Objective-C 2.0》第二章阅读笔记(2) <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
